package com.codefish.controller;

import com.aliyun.oss.OSSClient;
import com.codefish.annotation.PassToken;
import com.codefish.config.AliyunClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @Classname UploadController
 * @Description 图片上传
 * @Date 2021/5/3 19:10
 * @Created 学兔斯基眯眼看世界
 */
@RestController
@RequestMapping("/upload")
public class UploadController {


    @Autowired
    private OSSClient ossClient;

    @Autowired
    private AliyunClient aliyunClient;

    @PassToken
    @PostMapping(value = "/oss")
    public String ossUpload(@RequestParam("file") MultipartFile file
            ,@RequestParam(value = "folder",required = false) String folder) {
        String bucketName = aliyunClient.getBucketName();
        if (StringUtils.isEmpty(folder)){
            folder = "brand";
        }
        String fileName = folder + "/" + UUID.randomUUID() + "_" + file.getOriginalFilename();
        try {
            ossClient.putObject(bucketName, fileName, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "http://" + bucketName + "." + ossClient.getEndpoint().toString().replace("http://", "") + "/" + fileName;
    }


}
